package t_349

import (
	"go-source-learn/src/structure"
	"sort"
)

/**
合并数组求交集
*/
func getIntersection(array1, array2 []int) (intersection []int) {
	//
	set1 := structure.BuildSetByMap()

	for _, v := range array1 {
		set1[v] = struct{}{}
	}
	set2 := structure.BuildSetByMap()
	for _, v := range array2 {
		set2[v] = struct{}{}
	}

	if len(set1) > len(set2) {
		set1, set2 = set2, set1
	}
	for v := range set1 {
		if _, has := set2[v]; has {
			intersection = append(intersection, v)
		}
	}
	return
}

func getIntersectionByPoint(array1, array2 []int) []int {

	// sort by asc
	sort.Ints(array1)
	sort.Ints(array2)

	var result []int

	// 指针
	index1 := 0
	index2 := 0

	// 指针移动到相同部分 取值 双指针同时后移
	for index1 < len(array1) && index2 < len(array2) {
		if array1[index1] == array2[index2] {
			// 指针为0的时候直接放入新数组
			if index1 == 0 {
				result = append(result, array1[index1])

				/*	指针不为0的时候需要判断存放值是否已存在新数组中
					存在则忽略
					不存在就放入
				*/
			} else {
				if array1[index1-1] != array1[index1] {
					result = append(result, array1[index1])
				}
			}
			index1++
			index2++
		} else if array1[index1] < array2[index2] {
			index1++
		} else {
			index2++
		}

	}

	return result
}

/**
Advanced
*/

func intersection(nums1 []int, nums2 []int) []int {
	var res []int
	for _, each := range nums1 {
		if inArray(each, nums2) && !inArray(each, res) {
			res = append(res, each)
		}
	}
	return res

}
func inArray(num int, nums []int) bool {
	isIn := false
	for _, each := range nums {
		if each == num {
			return true
		}
	}
	return isIn
}
